#include "LinkList.h"
#include <stdio.h>

template <typename T>
LinkList<T>::LinkList(void)
{
        head = new Node<T>;
        head->next = NULL;
        len = 0;
}

template <typename T>
LinkList<T>::~LinkList(void)
{
        Node<T>* tmp = NULL;
        while (head != NULL){
                tmp = head->next;//删除链表节点的时候 缓存后面的节点
                delete head;
                head = tmp;
        }
        len = 0;
        head = NULL;
}

template <typename T>
void LinkList<T>::clear()
{
        Node<T>* tmp = NULL;
        while (head != NULL){
                tmp = head->next;//删除链表节点的时候 缓存后面的节点
                delete head;
                head = tmp;
        }
        
        head = new Node<T>;
        head->next = NULL;
        len = 0;
}

template <typename T>
int LinkList<T>::getLen()
{
        return len;
}

template <typename T>
int LinkList<T>::insert(T &t, int pos)
{
        Node<T>* current = NULL;
        current = head;
        if(pos < 0){ 
                return -1;
        }
        for (int i = 0; i < pos; i++){
                current = current->next;       
        }
        //思考 node节点存在吗?
        Node<T>* node = new Node<T>;
        if(node == NULL){
                return -1;
        }
        node->t = t; //缓存外部数据
        node->next = NULL;
        //1.让新插入node连接后续链表
        node->next = current->next;
        //2. 让前面的链表 连接新的node节点
        current->next = node;
        len++;
        return 0;
}

template <typename T>
int LinkList<T>::get(int pos,T &t)
{
        Node<T>* current = NULL;
        current = head;
        if(pos < 0){ 
                return -1;
        }
        for (int i = 0; i < pos; i++){
                current = current->next;       
        }
        t = current->next->t;//把缓存的t 传给调用者
        return 0;
}

template <typename T>
int LinkList<T>::del( int pos, T &t)
{
        Node<T>* current = NULL;
        Node<T>* ret = NULL;
        current = head;
        if(pos < 0){ 
                return -1;
        }
        for (int i = 0; i < pos; i++){
                current = current->next;       
        }
        ret = current->next; //被删除的元素
        t = ret->t; //把缓存的t拷贝出来
        
        current->next = ret->next;
        
        len--;

        delete ret;
        return 0;
}